package cn.growthgate.fgo.web;

import java.util.Arrays;

import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;

import cn.growthgate.fgo.common.Constants;
import cn.growthgate.fgo.entity.Cv;
import cn.growthgate.fgo.service.ICvService;
import cn.growthgate.fgo.util.StringUtils;
import cn.growthgate.fgo.web.result.JsonResult;
import cn.growthgate.fgo.web.result.TableResult;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author GrowthGate
 * @since 2019-05-24
 */
@Controller
@RequestMapping("/cv")
@RequiresRoles(value = {Constants.ROLE_ADMIN}, logical = Logical.OR)
public class CvController {

	@Autowired
	private ICvService cvService;

	@RequestMapping("/list")
	public ModelAndView list() {
		return new ModelAndView("cv/list");
	}

	@ResponseBody
	@RequestMapping("/tableData")
	public TableResult<Cv> tableData(Cv cv, Integer current, Integer size, String orderByField, Boolean isAsc) {
		Wrapper<Cv> wrapper = new EntityWrapper<>();

		if (StringUtils.isNotBlank(cv.getName())) {
			wrapper.like("name", cv.getName());
		}

		Page<Cv> page = cvService.selectPage(current, size, orderByField, isAsc, wrapper);
		return new TableResult<Cv>(page);
	}

	@RequestMapping("/form")
	public ModelAndView form(Long id) {
		Cv entity = cvService.selectById(id);

		return new ModelAndView("cv/form").addObject("entity", entity);
	}

	@ResponseBody
	@RequestMapping("/save")
	public JsonResult save(@Validated Cv cv, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return JsonResult.fail(bindingResult.getAllErrors().get(0).getDefaultMessage());
		}
		cvService.insertOrUpdate(cv);
		return JsonResult.ok();
	}

	@ResponseBody
	@RequestMapping("/delete")
	public JsonResult delete(Long[] ids) {
		if (cvService.deleteBatchIds(Arrays.asList(ids))) {
			return JsonResult.ok("删除成功");
		} else {
			return JsonResult.fail("删除失败");
		}
	}

}
